import cv2 as cv


#gloable
def equalize_histogram(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    dst = cv.equalizeHist(gray)
    cv.imshow('equalized-hist',dst)


def clahe_histogram(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    clahe = cv.createCLAHE(clipLimit=3, tileGridSize=(8,8))
    dst = clahe.apply(gray)
    cv.imshow('clahe_histogram',dst)


def cal_bgr_hist(image):
    hsv_image = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    h_bins = 50
    s_bins = 60
    hist_size = [50,60]
    # hue varies from 0 to 179, saturation from 0 to 255
    h_ranges = [0, 180]
    s_ranges = [0, 256]
    ranges = h_ranges + s_ranges  # concat lists
    channals = [0,1 ]
    hist = cv.calcHist([hsv_image],channals,None,hist_size,ranges,accumulate=False)
    cv.normalize(hist,hist,alpha=0,beta=1,norm_type=cv.NORM_MINMAX)
    return hist


def compare_hist(image1, image2):
    bhatta = cv.compareHist(cal_bgr_hist(image1), cal_bgr_hist(image2),cv.HISTCMP_BHATTACHARYYA)
    correl = cv.compareHist(cal_bgr_hist(image1),cal_bgr_hist(image2),cv.HISTCMP_CORREL)
    chisqr = cv.compareHist(cal_bgr_hist(image1),cal_bgr_hist(image2),cv.HISTCMP_CHISQR)
    print("bhatta: %s, correl: %s, chisqr %s"%(bhatta,correl,chisqr))


src = cv.imread('rubberwhale1.png', 1)
cv.namedWindow('demo', cv.WINDOW_AUTOSIZE)
cv.imshow('demo', src)
src2 = cv.imread('rubberwhale2.png', 1)
cv.imshow('image2',src2)
# equalize_histogram(src)
# clahe_histogram(src)
compare_hist(src, src2)

cv.waitKey(0)
cv.destroyWindow('demo')
